<template>
  <h1>姓名：{{ name }}</h1>
  <h1>年龄：{{ age }}</h1>
  <h1>薪资：{{ job.j1.salary }}K</h1>
  <button @click="name += '1'">点我修改姓名</button>
  <button @click="age++">点我修改年龄</button>
  <button @click="job.j1.salary++">涨薪</button>
  <hr />
  <div v-show="person.car">
    <span>车辆信息：{{ person.car }}</span>
    <button @click="changeCarInfo">改变车辆信息</button>
  </div>
  <button @click="showRow">打印原始数据</button>
  <button @click="addCar">添加车辆信息</button>
  <button @click="addRawCar">添加车辆信息并标记为原始信息</button>
</template>

<script>
import { reactive, ref, toRefs, toRaw, markRaw } from "vue";
export default {
  name: "Demo",
  setup() {
    console.log("setup");
    let person = reactive({
      name: "张三",
      age: 18,
      job: {
        j1: {
          salary: 20,
        },
      },
    });

    const x1 = ref({
      y: {
        z: 1,
      },
    });

    const x2 = ref(0);

    const showRow = () => {
      // toRow 只能获取reactive对象中的原始对象，
      console.log("person toRaw", toRaw(person));
      // 不能获取ref对象中的原始对象
      //   console.log("x1 toRaw", toRaw(x1));
      //   console.log("x2 toRaw", toRaw(x2));
    };

    const addCar = () => {
      // 将reactive对象中的car属性变成ref对象
      person.car = {
        name: "奔驰",
        price: 40,
      };
    };

    const changeCarInfo = () => {
      // 将reactive对象中的job对象变成原始对象
      person.car.name += "!";
      person.car.price++;
    };

    const addRawCar = () => {
      console.log("markRawCar");
      // 将reactive对象中的job对象变成原始对象
      console.log(toRaw(person.car));
      console.log(markRaw(toRaw(person.car)));
      console.log(
        markRaw({
          name: "奔驰",
          price: 40,
        })
      );
      person.car = markRaw({
        name: "奔驰",
        price: 40,
      });
      // 下面这种方式无效
      //   person.car = markRaw(toRaw(person.car));
    };

    return {
      // 将对象中的所有属性转成ref对象，并且可以修改
      person,
      ...toRefs(person),
      showRow,
      addCar,
      changeCarInfo,
      addRawCar,
    };
  },
};
</script>
